package com.api.chatai.utils;
import cn.hutool.jwt.Claims;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {

    //   token 时效时长  365 * 24 * 60 * 60 * 1000
    private static long tokenExpiration = 3 * 24 * 60 * 60 * 1000;

    private static String tokenSignKey = "20_pressure_detection_24";


    //    生成token
    public static String createToken(Integer userId) {
        String token = Jwts.builder()

                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))

                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
//                压缩字符串
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }


    //    从token获取用户id
    public static Integer getUserId(String token) {
        try {
            if (!StringUtils.hasText(token)) return null;

            Jws<io.jsonwebtoken.Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = (Claims) claimsJws.getBody();
            Integer userId = (Integer) claims.getClaim("userId");
            return userId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    public static void main(String[] args) {
        String token = JwtHelper.createToken(1);
        System.out.println(token);
        System.out.println("userId  :" + JwtHelper.getUserId(token));

    }
}